package com.cooldatasoft.taskManager.component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import com.cooldatasoft.domain.model.Project;
import com.cooldatasoft.domain.service.UserProjectRolesService;
import com.cooldatasoft.security.TaskManagerSecurityManager;
import com.cooldatasoft.support.git.FileNodeInterface;
import com.cooldatasoft.support.git.JavaGitManager;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.TreeTable;

@Configurable(preConstruction = true)
public class SourceControlViewBackup extends CustomComponent {
	private static final long serialVersionUID = 67L;

	private Project myCurrentProject;
	private String repositoryPathPrefix;
	
	@Autowired
	private UserProjectRolesService uprService;
	@Autowired
	private TaskManagerSecurityManager securityManager;
	
	private String projectName;
	private long projectId;

	private AbsoluteLayout mainLayout;
	private Label  topMessage;
	private NativeButton createDelteRepoButton;
	private TreeTable treetable;
	
	//header constants
	private static final String FILE_NAME_PROPERTY = "Name";
    private static final String FILE_SIZE_PROPERTY = "Size";
    private static final String LAST_MODIFIED_PROPERTY = "Last Modified";

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	public SourceControlViewBackup(Project project) {
		this.myCurrentProject = project;
		try {
			repositoryPathPrefix = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ":";
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		this.projectName = project.getName().replace(" ", "-");
		this.projectId = project.getIdProject();
		
		buildMainLayout();		
	}

	private void buildMainLayout() {
		JavaGitManager manager = JavaGitManager.getInstance();
		boolean projectExists = manager.existProject(
				projectName, projectId);
		
		// common part: create layout
		mainLayout = new AbsoluteLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(false);

		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");
		
		topMessage = new Label();
		topMessage.setStyleName("taskHeader");
		topMessage.setImmediate(false);
		topMessage.setWidth("80.0%");
		topMessage.setHeight("-1px");
		
		createDelteRepoButton = new NativeButton();
		createDelteRepoButton.setStyleName("defaultBtn");
		createDelteRepoButton.setImmediate(true);
		createDelteRepoButton.setWidth("-1px");
		createDelteRepoButton.setHeight("-1px");
		
		if (projectExists) {
			topMessage.setValue("Repository for you project is located here: " + repositoryPathPrefix + projectName + "_" + myCurrentProject.getIdProject());
			createDelteRepoButton.setCaption("Delete repository");
			createDelteRepoButton.addListener(getDeleteRepositoryActionListener());
			initTreeTable();
			mainLayout.addComponent(treetable);
		} else {
			topMessage.setValue("The repository for current project was not created yet. " +
								"\nClick the button below to create repository for your project.");
			createDelteRepoButton.setCaption("Create repository");
			createDelteRepoButton.addListener(getCreateRepositoryActionListener());
		}
		mainLayout.addComponent(topMessage);
		mainLayout.addComponent(createDelteRepoButton);
		
		setCompositionRoot(mainLayout);		
	}
	
	private void initTreeTable() {
        treetable = new TreeTable();
        treetable.setWidth("100%");

        // Add Table columns
        treetable.addContainerProperty(FILE_NAME_PROPERTY, String.class, "");
        treetable.addContainerProperty(FILE_SIZE_PROPERTY, String.class, "0 KB");
        treetable.addContainerProperty(LAST_MODIFIED_PROPERTY, Date.class, Calendar.getInstance().getTime());
        FileNodeInterface root = JavaGitManager.getInstance().getRepositoryStructureForProject(projectName, projectId);        
        fillTreeTable(root, null);
	}
	

	private void fillTreeTable(FileNodeInterface root, Object parent) {
		Object fileNode;
		
		if (root.isDirectory()) {
            List<FileNodeInterface> children = root.getChildren();
            fileNode = treetable.addItem(new Object[]{root.getName(),	"", root.lastModified()}, null);
            treetable.setChildrenAllowed(fileNode, true);           
            
            for (FileNodeInterface child : children) {
                fillTreeTable(child, fileNode);
            }            
        } else {
        	fileNode = treetable.addItem(new Object[]{root.getName(),	String.format("%.2f", root.getSize()) + "KB", root.lastModified()}, null);
        	treetable.setChildrenAllowed(fileNode, false);
        }
		
		if (parent != null) {
        	treetable.setParent(fileNode, parent);
        }
	}

	private ClickListener getDeleteRepositoryActionListener() {
		@SuppressWarnings("serial")
		ClickListener listener = new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				JavaGitManager.getInstance().deleteRepository(projectName, projectId);
				buildMainLayout();
			}
		};		
		return listener;
	}
	
	private ClickListener getCreateRepositoryActionListener() {
		@SuppressWarnings("serial")
		ClickListener listener = new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				JavaGitManager.getInstance().createRepository(projectName, projectId);
				buildMainLayout();
			}
		};		
		return listener;
	}
}
